package com.example.liyun.joy;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;

import java.lang.reflect.Method;

public class SearchActivity extends AppCompatActivity {

    private SearchView mSearchView;
    private SearchView.SearchAutoComplete mSearchAutoComplete;//搜索框变量
    private WebView mWebView;
    private WebSettings mWebSettings;
    private GridLayout mGridLayout;
    private Toolbar searchToolbar;
    //播放视频全屏需要的参数
    //设定FrameLayout的长宽铺满全屏父容器即getWindow();
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS=
            new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;//webView播放视频全屏的视图
    private FrameLayout fullVideoContainer;//用于加载contentParentView的容器
    private WebChromeClient.CustomViewCallback customViewCallback;//用户调用此回调以请求页面退出全屏模式。

    private String url="https://www.baidu.com/s?wd=";//搜索的url链接


    private WebViewClient mWebViewClient;//处理各种通知 & 请求事件
    private WebChromeClient mWebChromeClient;//辅助处理JavaScript的一个类

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        searchToolbar=findViewById(R.id.search_toolbar);
        super.setSupportActionBar(searchToolbar);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            WindowManager.LayoutParams barLayoutParams=getWindow().getAttributes();
            barLayoutParams.flags=(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS|barLayoutParams.flags);
        }
        //去除默认title
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mSearchView=findViewById(R.id.search_view);
        mGridLayout=findViewById(R.id.search_list);

        //SearchView的初始化并设置
        initSearchView();
        //webView网页加载视窗
        initWebView();

        initRecycleItem();

    }

    /**
     * 用于RecycleView的Item点击监听事件的跳转传递数据
     */
    public void initRecycleItem(){
        String itemUrl=getIntent().getStringExtra("url");
        Log.i("itemUrl","SearchWebView:"+itemUrl);
        if (itemUrl!=null){
            startWebView(itemUrl);
        }
    }

    private void initSearchView() {
        //直接展开显示在toolbar上
        mSearchView.onActionViewExpanded();
        //右侧显示搜索提交按钮
        mSearchView.setSubmitButtonEnabled(true);
        //设置提交按钮图标
        ImageView mSubmit=mSearchView.findViewById(R.id.search_go_btn);
        //得到ImageButton，重新设置显示的图标
        mSubmit.setImageResource(R.drawable.ic_search);
        //设置提示title
        mSearchView.setQueryHint("搜索内容");
        //通过Id得到搜索框控件
        mSearchAutoComplete=mSearchView.findViewById(R.id.search_src_text);

        //退出搜索界面
        searchToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果搜索框中有文字，则会先清空文字，但网易云音乐是在点击返回键时直接关闭搜索框
                if (mSearchAutoComplete.isShown()){//判断搜索框是否展开显示
                    try {
                        //清空搜索框文字
                        mSearchAutoComplete.setText("");
                        //调取SearchView的关闭方法
                        Method method=mSearchView.getClass().getDeclaredMethod("onCloseClicked");
                        method.setAccessible(true);//启用该方法
                        method.invoke(mSearchView);//绑定
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else {
                    finish();
                }
            }
        });

        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            //点击提交按钮时执行此方法，输入框得有内容才能触发提交
            @Override
            public boolean onQueryTextSubmit(String s) {
                url=url+s;
                startWebView(url);
                return false;
            }
            //输入框内容发生改变时，触发此方法响应
            @Override
            public boolean onQueryTextChange(String s) {
                return false;
            }
        });
    }

    public void startWebView(String url){
        mGridLayout.setVisibility(View.GONE);
        mWebView.setVisibility(View.VISIBLE);
        mWebView.loadUrl(url);
    }

    public void setSearchType(View view){
        switch (view.getId()){
            case R.id.video:
                mSearchView.setQueryHint("视频");
                url="https://www.baidu.com/sf/vsearch?pd=video&wd=";
                break;
            case R.id.image_content:
                mSearchView.setQueryHint("图片");
                url="https://www.baidu.com/sf/vsearch?pd=image_content&atn=page&wd=";
                break;
            case R.id.wenda_tab:
                mSearchView.setQueryHint("问答");
                url="https://www.baidu.com/sf/vsearch?pd=wenda_tab&wd=";
                break;
            case R.id.tieba:
                mSearchView.setQueryHint("贴吧");
                url="https://www.baidu.com/sf/vsearch?pd=tieba&wd=";
                break;
            case R.id.realtime:
                mSearchView.setQueryHint("资讯");
                url="https://www.baidu.com/sf/vsearch?pd=realtime&wd=";
                break;
            case R.id.wenku:
                mSearchView.setQueryHint("文库");
                url="https://www.baidu.com/sf/vsearch?pd=wenku&wd=";
                break;
            case R.id.xsp:
                mSearchView.setQueryHint("小视频");
                url="https://www.baidu.com/sf/vsearch?pd=xsp&atn=index&wd=";
                break;
            case R.id.map:
                mSearchView.setQueryHint("地图");
                url="https://www.baidu.com/sf/vsearch?pd=map&wd=";
                break;
            case R.id.music:
                mSearchView.setQueryHint("音乐");
                url="https://www.baidu.com/sf/vsearch?pd=music&wd=";
                break;
        }
    }


    private void initWebView() {
        mWebView=findViewById(R.id.wb_search_content);
        //contentParentView= this.<View>findViewById(android.R.id.content);
        mWebSettings=mWebView.getSettings();//webView 设置工具类
        //加载连接
        //mWebView.loadUrl("https://www.baidu.com/s?wd=谷歌翻译");

        //设置不用系统浏览器打开,直接显示在当前Webview
        mWebView.setWebViewClient(new WebViewClient(){

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.getUrl().toString());
                return true;
            }
        });

        //设置支持javascript脚本
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setAppCacheEnabled(true);
        //使用内置的缩放机制
        mWebSettings.setBuiltInZoomControls(true);
        //控制是否显示这些控件
        mWebSettings.setDisplayZoomControls(true);
        //设置返回上一页，而不是直接退出
        mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

        //适配手机屏幕设置
        mWebSettings.setUseWideViewPort(true);//设定支持viewport
        mWebSettings.setLoadWithOverviewMode(true);//自适应屏幕,是否调节内容 是否全屏
        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        mWebView.setWebViewClient(new WebViewClient(){
            //在页面加载完毕时，隐藏不需要显示的部分,需要整个页面加载完毕才会隐藏
            @Override
            public void onPageFinished(final WebView view, final String url) {

                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        //view.loadUrl("javascript:alert(document.getElementById('head_wrapper'));");
                        hideHtml(view,url);
                    }
                });
                super.onPageFinished(view, url);
            }
        });
        //当页面加载进度发生改变时，隐藏。当加载完成隐藏部分的标签时，就会隐藏，不用等整个页面加载完成
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.i("webViewUrl",view.getUrl());
                hideHtml(view,view.getUrl());
                super.onProgressChanged(view, newProgress);
            }

            /**
             *在缓存全屏视频时获得要显示的视图。
             * @return
             */
            @Override
            public View getVideoLoadingProgressView() {
                //动态添加一个全屏视频要显示的容器View
                FrameLayout frameLayout=new FrameLayout(SearchActivity.this);
                //设置要显示的View视图的填充模式
                frameLayout.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
                return frameLayout;
            }

            /**
             *当前页面进入全屏模式时，调用此方法
             * @param view    全屏模式下显示的View
             * @param callback  一个接口，可以调用这个接口请求关闭全屏模式
             */
            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                showCustomView(view,callback);
                //super.onShowCustomView(view, callback);
            }

            /**
             *通知应用当前页面已经关闭全屏模式，需要对显示的View容器进行隐藏
             */
            @Override
            public void onHideCustomView() {
                hideCustomView();
                //super.onHideCustomView();
            }
        });
    }

    /**
     * 显示视频全屏播放的方法
     * @param view  要显示的View对象
     * @param callback 调用此回调以请求页面退出全屏模式
     */
    public void showCustomView(View view, WebChromeClient.CustomViewCallback callback){
        //先判断如果视图已存在，则立即终止新视图
        if (customView!=null){
            callback.onCustomViewHidden();
            return;
        }
        //获取手机屏幕视窗
        SearchActivity.this.getWindow().getDecorView();

        FrameLayout decor= (FrameLayout) getWindow().getDecorView();
        fullVideoContainer=new FullVideoHolder(SearchActivity.this);
        fullVideoContainer.addView(view,COVER_SCREEN_PARAMS);
        decor.addView(fullVideoContainer,COVER_SCREEN_PARAMS);
        //设置横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        customView=view;//存在全屏视图
        setStatusBarVisibility(false);//全屏播放时隐藏状态栏
        customViewCallback=callback;
    }

    /**
     * 隐藏视频全屏
     */
    public void hideCustomView(){
        if (customView==null){
            return;
        }
        //设置竖屏模式
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setStatusBarVisibility(true);//显示状态栏
        FrameLayout decor= (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullVideoContainer);//从容器中删除显示全屏的容器ViewGroup
        fullVideoContainer=null;
        customView=null;
        customViewCallback.onCustomViewHidden();//回调退出全屏
        mWebView.setVisibility(View.VISIBLE);


    }

    /**
     * 设置是否显示状态栏,并设置全屏模式
     * @param visible
     */
    private void setStatusBarVisibility(boolean visible){
        int flag=visible?0:WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    //

    /**
     * 利用与js交互，隐藏部分html内容
     * @param view
     * @param url
     */
    public void hideHtml(WebView view,String url){
        String fun="javascript:function getClass(parent,sClass) { var aEle=parent.getElementsByTagName('div'); var aResult=[]; var i=0; for(i<0;i<aEle.length;i++) { if(aEle[i].className==sClass) { aResult.push(aEle[i]); } }; return aResult; }void(0) ";
        view.loadUrl(fun);
        if(url!=null&&url.contains("baidu.com")){
            String fun2="javascript:function hideOther() { getClass(document,'se-head-logo')[0].style.display='none';getClass(document,'searchboxtop')[0].style.display='none'; getClass(document,'page-banner')[0].style.display='none';getClass(document,'se-page-copyright')[0].style.display='none';}";
            view.loadUrl(fun2);
            view.loadUrl("javascript:hideOther();");
            Log.d("aaa","进入执行");
        }else if (url!=null&&url.contains("mini.eastday.com")){
            String fun3="javascript:function hideOther() { getClass(document,'articledown-wrap')[0].style.display='none';getClass(document,'container')[0].style.display='none'; }";
            view.loadUrl(fun3);
            view.loadUrl("javascript:hideOther();");
        }
    }



    /**
     * 改写物理返回键逻辑，返回的时候，是返回webview历史页面，而不是直接finish（）
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        /**
         * 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面
         */
        if (keyCode==KeyEvent.KEYCODE_BACK&&customView!=null){
            hideCustomView();
        }else if (keyCode==KeyEvent.KEYCODE_BACK&&mWebView.canGoBack()){
            //返回上一页
            mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            mWebView.goBack();
        }else {
            mGridLayout.setVisibility(View.VISIBLE);
            mWebView.setVisibility(View.GONE);
            finish();
        }
        return true;
    }

    @Override
    protected void onResume() {
        mWebView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mWebView.onPause();
        super.onPause();
    }
}
